package org.zhaolei.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.zhaolei.enums.CouponCategoryEnum;
import org.zhaolei.request.NewUserCouponRequest;
import org.zhaolei.service.CouponService;
import org.zhaolei.util.JsonData;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api("优惠券模块")
@RestController
@RequestMapping("api/coupon/v1")
@Slf4j
public class CouponController {

    @Autowired
    CouponService couponService;

    @Autowired
    RedissonClient redissonClient;

    @ApiOperation("分页查询优惠券")
    @GetMapping("page_coupon")
    public JsonData pageCouponList(
            @ApiParam(value = "当前页") @RequestParam(value = "page", defaultValue = "1") int page,
            @ApiParam(value = "每页显示多少条") @RequestParam(value = "size", defaultValue = "10") int size
    ) {
        Map<String, Object> pageMap = couponService.pageCouponActivity(page, size);
        return JsonData.buildSuccess(pageMap);
    }

    /**
     * 领取优惠券
     * @param couponId
     * @return
     */
    @ApiOperation("领取优惠券")
    @GetMapping("/add/promotion/{coupon_id}")
    public JsonData addPromotionCoupon(@ApiParam(value = "优惠券id", required = true) @PathVariable("coupon_id") long couponId) {

        JsonData jsonData = couponService.addCoupon(couponId, CouponCategoryEnum.PROMOTION);
        return jsonData;
    }

    /**
     * 新用户领取优惠券
     * @param newUserCouponRequest
     * @return
     */
    @ApiOperation("RPC-领取新用户优惠券")
    @PostMapping("/new_user_coupon")
    public JsonData addNewUserCoupon(@ApiParam("用户对象") @RequestBody NewUserCouponRequest newUserCouponRequest) {

        JsonData jsonData = couponService.initNewUserCoupon(newUserCouponRequest);

        return jsonData;
    }

    @GetMapping("lock")
    public JsonData testLock(){
        //可以开两个线程，同时访问这个接口，会发现一个能访问成功一个不能，等前一个的锁解除了之后，后一个线程就能访问了
        RLock lock = redissonClient.getLock("lock:coupon:1");

        //阻塞等待
        //lock.lock(10,TimeUnit.MILLISECONDS);
        lock.lock();

        try {

            log.info("加锁成功，处理业务逻辑。。。。。。"+Thread.currentThread().getId());
            TimeUnit.SECONDS.sleep(20);

        }catch (Exception e){

        }finally {
            log.info("解锁成功，其他线程可以进去。。。。。。"+Thread.currentThread().getId());
            lock.unlock();
        }

        return JsonData.buildSuccess();

    }
}


